package com.superatom.concurrent.basic.callable;

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 启动带返回值的线程
 */
public class CallableDemo {
    public static void main(String[] args){
        ExecutorService exec = Executors.newCachedThreadPool();
        ArrayList<Future<String>> results = new ArrayList<Future<String>>();

        for (int i = 0; i < 10; i++){
            // submit()方法会产生Future对象，是Callable的返回结果
            results.add(exec.submit(new TaskWithResult(i)));
        }

        for (Future<String> fs : results){
            try {
                // 获取线程返回值，如果没有返回值，get()将阻塞，直至结果准备就绪
                System.out.println(fs.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }finally {
                exec.shutdown();
            }
        }
    }
}

/**
 * 实现Callable接口，可以在任务执行完成后返回一个值
 * 必须实现call方法
 */
class TaskWithResult implements Callable<String>{
    private int id;

    public TaskWithResult(int id){
        this.id = id;
    }

    public String call() throws Exception {
        return "result of TaskWithResult " + id;
    }
}
